import GameMgr from "./gameMgr";

const { ccclass, property } = cc._decorator;

@ccclass
export default class musicMgr {

    // 当前播放的背景音乐id
    bgmId = -1

    // 背景音乐的音量大小
    bgmVolume = 1.0

    // 背景音效的音量大小
    effectVolume = 1.0

    init() {
        // 监听是否会最小化
        cc.game.on(cc.game.EVENT_HIDE, () => {
            cc.audioEngine.pauseAll()
        })
        cc.game.on(cc.game.EVENT_SHOW, () => {
            cc.audioEngine.resumeAll()
        })
    }

    playBgm(url) {
        let audioUrl = "music/" + url
        // 如果当前已经在播放bgm了 那么切换bgm
        if (this.bgmId >= 0) {
            cc.audioEngine.stop(this.bgmId)
        }
        let clip = GameMgr.instance.audioClip[audioUrl]
        if (clip) {
            this.bgmId = cc.audioEngine.play(clip, true, this.bgmVolume)
        } else {
            cc.loader.loadRes(audioUrl, cc.AudioClip, (err, clip) => {
                if (!err) {
                    this.bgmId = cc.audioEngine.play(clip, true, this.bgmVolume)
                    GameMgr.instance.audioClip[audioUrl] = clip
                } else {
                    console.log(err, "音乐加载失败");
                }
            })
        }
    }

    playEffect(url){
        let audioUrl = "music/" + url
        let clip = GameMgr.instance.audioClip[audioUrl]
        if (clip) {
            cc.audioEngine.play(clip, false, this.bgmVolume)
        } else {
            cc.loader.loadRes(audioUrl, cc.AudioClip, (err, clip) => {
                if (!err) {
                    cc.audioEngine.play(clip, false, this.bgmVolume)
                    GameMgr.instance.audioClip[audioUrl] = clip
                } else {
                    console.log(err, "音效加载失败");
                }
            })
        }
    }

    setBgmVolume(v){
        this.bgmVolume = v
        cc.audioEngine.setVolume(this.bgmId,v)
    }

    setEffectVolume(v){
        this.effectVolume = v
    }


}
